<template>
    <vp-card class="w100">
        <template #header>
            <slot name="header"></slot>
        </template>
        <slot>
        </slot>
        <vp-table :data="props.attachmentList" v-loading="uploadLoading" :height="height" element-loading-text="上传中，请稍后.../Uploading, please wait...">
            <el-table-column  type="index" align="center" label="#">
            </el-table-column>
            <el-table-column :label="$t('item.fileName')">
                <template #header><vp-label zh="文件名" en="File Name"/></template>
                <template #default="scope">
                    <el-link @click="handleFileClick(scope.row)">
                        <span v-html="scope.row.wbwjm + (scope.row.hzm? '.' + scope.row.hzm : '')"></span>
                    </el-link>
                    <el-progress type="circle" width="60" :percentage="scope.row.progress"  v-if="scope.row.showRow"/>
                </template>
            </el-table-column>
            <el-table-column prop="yqsc" width="200">
                <template #header><vp-label zh="要求时长(分钟)" en="Request Duration(minute)"/></template>
                <template #default="scope">
                    <el-form-item :prop="`attachmentList[${scope.$index}].yqsc`" label-width="auto">
                        <el-input v-if="!props.readOnly"  @input="(val:string) => {scope.row.yqsc = verifiyNumberInteger(val) }" @blur="changeYqsc(scope.$index, scope.row)"  v-model="scope.row.yqsc" v-trim maxlength="12" >
                        </el-input>
                        <span v-else >{{ scope.row.yqsc }}</span>
                    </el-form-item>
                </template>
            </el-table-column>
            <el-table-column prop="wjdx" width="150">
                <template #header><vp-label zh="文件大小" en="File Size"/></template>
                <template #default="scope">
                    {{scope.row.wjdx + " KB"}}
                </template>
            </el-table-column>
            <el-table-column prop="czsj" width="160">
                <template #header><vp-label zh="上传时间" en="Upload Time"/></template>
            </el-table-column>
            <el-table-column v-if="!props.readOnly" :label="$t('item.operation')" align="center" width="60">
                <template #header>
                    <el-upload action="" :multiple="multiple" :before-upload="beforeUpload" :accept="accept" :show-file-list="false" v-if="!readOnly">
                        <el-button circle><SvgIcon name="ele-Plus"></SvgIcon></el-button>
                    </el-upload>
                </template>
                <template #default="scope">
                    <el-button v-if="deleteExist || !scope.row.mainid"  circle @click="deleteFile(scope.$index)"><SvgIcon name="ele-Minus"></SvgIcon></el-button>
                </template>
            </el-table-column>
        </vp-table>   
    </vp-card>
</template>
<script setup lang="ts" name="vpCoursewareCard">
    import {ref} from 'vue'
    import request from '/@/utils/request';
    import { Session } from '/@/utils/storage';
    import { useRouter } from 'vue-router';
    import { ElMessage } from 'element-plus';
    import { verifiyNumberInteger } from '/@/utils/toolsValidate';

    const props = withDefaults(defineProps<{
        attachmentList: any[], //附件列表
		readOnly?: boolean, //是否只读
        multiple?: boolean,
        accept?: string,
        disableDownload?: number,
        deleteExist?: boolean,
        height?: string,
    }>(), {
        readOnly: false,
        multiple: true,
        deleteExist: true,
    })

    const emits = defineEmits<{
        (event: 'attachmentListEmit', data: any[]): void
    }>()

    const uploadLoading = ref(false)

    const beforeUpload = (file: any) => {
        if (file) {
            uploadLoading.value = true
            let submitData = new FormData();
            submitData.append('file', file);
            request.post(`/file/upload`, submitData, { 
                headers: { 
                    'content-type': 'multipart/form-data',
                    token: `${Session.get('token') || ''}`
                }
            }).then(res => {
                if(res.data && res.data.length) {
                    let attachmentList = props.attachmentList ? props.attachmentList : [] as any[];
                    attachmentList = [...attachmentList, ...res.data];
                    emits('attachmentListEmit', attachmentList);
                }
            }).finally(()=>uploadLoading.value=false);
        }
        return false;
    };

    const deleteFile = (index: any) => {
        let attachmentList = props.attachmentList ? props.attachmentList : [];
        attachmentList.splice(index, 1);
        emits('attachmentListEmit', attachmentList);
    };

    const router = useRouter()
    const handleFileClick = (attachment: any) => {
        let viewType = '';
        if (attachment.hzm == 'PNG' || attachment.hzm == 'JPG' || attachment.hzm == 'BMP') {
          viewType="IMAGE"
        } else if (attachment.hzm == 'PDF') {
          viewType="PDF"
        } else if(attachment.hzm == "MP4"){
          viewType="VIDEO"
        } else if(attachment.hzm == "MP3"){
          viewType="AUDIO"
        }
        if(viewType !== ""){
          const {href} = router.resolve({
            name:"fileView",
            params: {
              id: attachment.id,
              type: viewType,
              disableDownload: props.disableDownload
            }
          })
          window.open(href, '_blank');
        }else{
            if (props.disableDownload === 1) {
                ElMessage.error("无权下载/No permission to download.");
            } else {
                downloadAttachment(attachment);
            }
        }

    };

    const downloadAttachment = (attachment: any) => {
        const fileUrl = `/api/file/download/${attachment.id}`;
        const link = document.createElement('a');
        link.href = fileUrl;
        link.setAttribute('download', attachment.wbwjm + (attachment.hzm? '.' + attachment.hzm : ''));
        link.click();
    };

    const changeYqsc = (index: any, row: any) =>{
        let attachmentList = props.attachmentList ? props.attachmentList : [];
        attachmentList[index].yqsc = row.yqsc; 
        emits('attachmentListEmit', attachmentList);
    }
</script>
<style scoped lang="scss">

</style>